package com.google.code.lightsomy.web;

import java.io.IOException;
import java.io.Writer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filter to restrict access to resources using regular expression passed as an init parameter.
 * 
 * @author Viktoras Agejevas
 *
 */
public class AccessFilter implements Filter {

	private FilterConfig config;
	
	private Pattern pattern;
	
	@Override
	public void destroy() {
		config = null;
		pattern = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 
			throws IOException, ServletException {

		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			
			if (pattern != null) {
				Matcher m = pattern.matcher(req.getRequestURI());
				
				if (m.matches()) {
					response.reset();
					if (response instanceof HttpServletResponse) {
						((HttpServletResponse) response).setStatus(
								HttpServletResponse.SC_FORBIDDEN);
					}
					response.setContentType("text/html; charset=UTF-8");
					append403ForbiddenHtml(response.getWriter());
					response.flushBuffer();
					return;
				}
			}
		}
		
		filterChain.doFilter(request, response);
	}
	
	private void append403ForbiddenHtml(Writer writer) throws IOException {
		writer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		writer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
		writer.append("    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
		writer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n");
		writer.append("<head>\n");
		writer.append("<title>403 access forbidden</title>\n");
		writer.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />\n");
		writer.append("<body>\n");
		writer.append("<h1>403 access forbidden</h1><p>This resource has no public access.</p>\n");
		writer.append("</body>\n");
		writer.append("</head>\n");
		writer.append("</html>");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
		String regex = config.getInitParameter("regex");
		
		if (regex != null) {
			pattern = Pattern.compile(regex);
		}
	}

}
